package com.android.fragmentdemo.util;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class LogService {
    private static String logPath = "";//日志存放路径
    private static final String templete="yyyy-MM-dd:HH:mm:ss";//时间格式
    private static final String TAG = "CyberLogService";
    private static String fileName = "";//文件名
    private static String fileName_up = "";//要上传的文件名
    private LogService() {}

    public static void init(Context context) {
        logPath = context.getFilesDir().getPath() + File.separator + "Logs";
        File file_dir = new File(logPath);
        if (!file_dir.exists()) {
            file_dir.mkdirs();
        }
        fileName = "cyber.log";
        fileName_up = "cyber_up.log";
        File file = new File(logPath, fileName);
        if (file.exists()) {
            //boolean copy_result = FileUtils.copyFile(file.getAbsolutePath(),logPath+File.separator+fileName_up);
            //if(!copy_result){
            //    LogService.e(TAG,"复制日志文件失败");
            //}else {
            //    file.delete();
            //}
        }
    }

    public static void i(String content){
        i(TAG,content);
    }

    public static void i(String tag,String content){
        //if(AppConstants.DEBUG_MODE){
        //    Log.i(tag,content+"");
        //}
        writeLogtoFile("INFO",tag,content);
    }

    public static void d(String content){
        d(TAG,content);
    }

    public static void d(String tag,String content){
        //if(AppConstants.DEBUG_MODE){
        //    Log.d(tag,content+"");
        //}
        writeLogtoFile("DEBUG",tag,content);
    }

    public static void e(String content){
        e(TAG,content);
    }

    public static void e(String tag,String content){
        //if(AppConstants.DEBUG_MODE){
        //    Log.e(tag,content+"");
        //}
        writeLogtoFile("ERROR",tag,content);
    }

    /**
     * 打开日志文件并写入日志
     * @param mylogtype i,d,e
     * @return
     * **/
    private static synchronized  void writeLogtoFile(String mylogtype, String tag, String text) {// 新建或打开日志文件
        if (TextUtils.isEmpty(logPath) || TextUtils.isEmpty(fileName)) {
            return;
        }

        Date nowDate = new Date(System.currentTimeMillis());
        String nowtime = new SimpleDateFormat(templete).format(nowDate);
        String needWriteMessage = "["+nowtime + "] [" + mylogtype
                + "] [" + tag + "] :" + text;
        File directory = new File(logPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(logPath,fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter filerWriter = new FileWriter(file, true);//后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
            bufWriter.write(needWriteMessage);
            bufWriter.newLine();
            bufWriter.close();
            filerWriter.close();
        } catch (IOException e) {
            Log.e(TAG, "写日志文件出错"+e.getMessage());
        }
    }

    /***
     * 上传日志文件
     */
    public static void uploadText() {
        File file = new File(logPath, fileName_up);
        if (!file.exists()) {
            LogService.e(TAG, "日志文件不存在，上传日志失败");
            return;
        }
        InputStream inputStream = null;
        byte[] buffer;
        try {
            inputStream = new FileInputStream(file);
            int max_length = inputStream.available();
            buffer = new byte[1024 * 1024 * 2];
            List<String> strList = new ArrayList<>();
            int length = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                //循环读取 数据
                String res = new String(buffer, 0, length);//encode
                Log.i(TAG, "循环打印上传日志:" + res);
                strList.add(res);
            }
            for (int i = 0; i < strList.size(); i++) {
                upload(strList.get(i), i == strList.size() - 1);
            }

        } catch (Exception e1) {
            LogService.e(TAG, "uploadFileByByteStr 文件读取失败fileName:" + e1.getMessage());
            e1.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    private static void upload(String res, final boolean needDelete) {
//        Map<String,Object> map = new HashMap<>();
//        map.put("clientInfo",AppConfig.UserID);
//        map.put("fileName",System.currentTimeMillis()+"");
//        map.put("fileContent",res);
//        HttpUtils.asyncPost(CyberUrl.UserLogUpload, new HttpUtils.HttpCallBack() {
//            @Override
//            public void onFailure(String message) {
//                Log.e(TAG,"日志文件上传失败:"+message);
//            }
//
//            @Override
//            public void onSuccess(String result) {
//                Log.e(TAG,"日志文件上传成功+needDelete:"+needDelete);
//                if(needDelete){
//                    File file = new File(logPath,fileName_up);
//                    if(file.exists())
//                        file.delete();
//                }
//            }
//        },map);
    }
}
